package com.next

import grails.converters.JSON
import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured
import sun.misc.BASE64Encoder

import javax.crypto.spec.SecretKeySpec

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR'])
class BillsController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def dataSource

    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        respond Bills.list(params), model: [billsCount: Bills.count()]
    }

    def show(Bills bills)
    {
        def billsItems = BillsItem.findAll("from BillsItem where bills.id = ${bills.id}) order by period asc")
        respond bills, model: [billsItems: billsItems]
    }

    def create()
    {
        respond new Bills(params)
    }

    @Transactional
    def save(Bills bills)
    {
        if (bills == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (bills.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond bills.errors, view: 'create'
            return
        }

        bills.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'bills.label', default: 'Bills'), bills.id])
                redirect bills
            }
            '*' { respond bills, [status: CREATED] }
        }
    }

    def edit(Bills bills)
    {
        respond bills
    }

    @Transactional
    def update(Bills bills)
    {
        if (bills == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (bills.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond bills.errors, view: 'edit'
            return
        }

        bills.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'bills.label', default: 'Bills'), bills.id])
                redirect bills
            }
            '*' { respond bills, [status: OK] }
        }
    }

    @Transactional
    def delete(Bills bills)
    {

        if (bills == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        bills.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'bills.label', default: 'Bills'), bills.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'bills.label',
                                                                                          default: 'Bills'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    /**
     * @Description: 为历史订单批量增加组件* @Params: null* @Return: null* @Author: Nagelan* @Datetime: 2018/9/6 000614:28
     */
    @Transactional
    def addNewComponentToOldOrders()
    {
        def db = new groovy.sql.Sql(dataSource)
        def component = Component.findByName("外贸预审")?.id
        if (component)
        {
            def flowIds = db.rows("SELECT off1.id from opportunity_flow off1 LEFT JOIN opportunity o ON off1.opportunity_id = o.id LEFT join opportunity_stage os ON off1.stage_id = os.id WHERE os.name = '审批已完成' AND o.status = 'Pending' AND off1.end_time IS NULL ")
            flowIds?.each {
                if (db.rows("SELECT id FROM opportunity_flow_condition WHERE component_id = ? AND flow_id = ?", [component, it[0]]).size() == 0)
                {
                    db.executeInsert("INSERT INTO opportunity_flow_condition VALUES(0,?,NULL,0,?,NULL,'外贸预审未通过',NULL)", [component, it[0]])
                }
            }
        }
    }

    /** @Description 中行项目对接百融接口（优客准入规则）
     * @Params null* @Return
     * @Author Nagelan* @DateTime 2018/12/23 0023 11:46
     */
    def jinjian = { mapData ->
        def result
        def map
        def opportunity = mapData.opportunity
        if (opportunity)
        {
            def sentHTTPRequest = { urlString, requestData, String header ->
                try
                {
                    def connection = (java.net.HttpURLConnection) urlString.openConnection()
                    connection.setDoOutput(true)
                    connection.setRequestMethod("POST")
                    connection.setRequestProperty("Content-Type", header)
                    connection.outputStream.withWriter("UTF-8") { java.io.Writer writer -> writer.write requestData }
                    connection.setConnectTimeout(60000)
                    result = grails.converters.JSON.parse(connection.inputStream.withReader("UTF-8") { java.io.Reader reader -> reader.text })
                    return result
                }
                catch (java.lang.Exception e)
                {
                    e.printStackTrace()
                    println(e)
                }
            }
            //获取token请求参数
            map = "grant_type=authorization_code&client_id=test&client_secret=123456"
            result = sentHTTPRequest(new java.net.URL("http://5q6zif.natappfree.cc/oauth/token"), map, "application/x-www-form-urlencoded")
            def token = result?.token
            println token
            if (token)
            {
                def contact
                def type = mapData.type
                def productCode
                if (type == "spouse")
                {
                    productCode = "000020190222521465"
                    contact = com.next.OpportunityContact.findByOpportunityAndType(opportunity, com.next.OpportunityContactType.findByName('借款人配偶'))?.contact
                }
                else
                {
                    productCode = "000020190107655959"
                    contact = opportunity?.contact
                }
                def name = contact?.fullName
                def phone_no = contact?.cellphone
                def id_card = contact?.idNumber
                def productType = opportunity?.product?.name
                def loanTimeLimit = opportunity?.loanDuration
                def loanAmount = opportunity?.requestedAmount
                def sceneCreditLimit = "200000"
                def age = opportunity?.contact?.age ? opportunity?.contact?.age : (new java.util.Date().format("yyyy").toInteger() - opportunity?.contact?.idNumber?.substring(6, 10)?.toInteger())
                map = [:]
                map.productCode = productCode
                map.clientId = "test"
                def requestParam = [:]
                requestParam.sysNumber = opportunity?.serialNumber
                requestParam.name = name
                requestParam.id_card = id_card
                requestParam.phone_no = phone_no
                requestParam.age = age
                requestParam.sceneCreditLimit = sceneCreditLimit
                requestParam.loanAmount = loanAmount ?: ""
                requestParam.productType = productType
                requestParam.loanTimeLimit = loanTimeLimit
                map.requestParam = requestParam
                map.token = token
                println "准入规则请求参数" + map.toString()
                result = sentHTTPRequest(new java.net.URL("http://5q6zif.natappfree.cc/decision/sync/get"), groovy.json.JsonOutput.toJson(map).toString(), "application/json")
                println "优客准入规则返回结果：" + result
                if (result?.stateCode == "00000" && opportunity)
                {
                    def opportunityFlexFieldCategory
                    def opportunityFlexField
                    if (result?.decisionResult?.result)
                    {
                        opportunityFlexField = com.next.OpportunityFlexField.findByNameAndCategory("百融欺诈决策结果", com.next.OpportunityFlexFieldCategory.findByOpportunityAndFlexFieldCategory(opportunity, com.next.FlexFieldCategory.findByName("百融欺诈决策结果")))
                        if (opportunityFlexField)
                        {
                            opportunityFlexField.value = result?.decisionResult?.result
                            def resultMap = [:]
                            if (type == "spouse")
                            {
                                resultMap.spouseRepaymentAmountM6 = result?.decisionResult?.param?.repaymentAmountM6
                                resultMap.spouseUunclearedMortgage = result?.decisionResult?.param?.unclearedMortgage
                                resultMap.spouseHouseAvgM6 = result?.decisionResult?.param?.houseAvgM6
                                resultMap.repaymentAmountM6 = ""
                                resultMap.unclearedMortgage = ""
                                resultMap.houseAvgM6 = ""
                            }
                            else
                            {
                                resultMap.spouseRepaymentAmountM6 = ""
                                resultMap.spouseUunclearedMortgage = ""
                                resultMap.spouseHouseAvgM6 = ""
                                resultMap.repaymentAmountM6 = result?.decisionResult?.param?.repaymentAmountM6
                                resultMap.unclearedMortgage = result?.decisionResult?.param?.unclearedMortgage
                                resultMap.houseAvgM6 = result?.decisionResult?.param?.houseAvgM6
                            }

                            opportunityFlexField.defaultValue = (resultMap as grails.converters.JSON)?.toString()
                            opportunityFlexField.save(flush: true)
                        }
                    }
                    if (result?.decisionResult?.param?.warningInfo)
                    {
                        opportunityFlexFieldCategory = com.next.OpportunityFlexFieldCategory.findByOpportunityAndFlexFieldCategory(opportunity, com.next.FlexFieldCategory.findByName("准入警示信息"))
                        if (opportunityFlexFieldCategory)
                        {
                            def i = 0
                            result?.decisionResult?.param?.warningInfo?.each {
                                opportunityFlexField = new com.next.OpportunityFlexField(name: it, description: "警示信息", dataType: "String", displayOrder: i, category: opportunityFlexFieldCategory)
                                opportunityFlexField.save(flush: true)
                                i++
                            }
                        }
                    }
                    if (result?.decisionResult?.param?.refuseReason)
                    {
                        opportunityFlexFieldCategory = com.next.OpportunityFlexFieldCategory.findByOpportunityAndFlexFieldCategory(opportunity, com.next.FlexFieldCategory.findByName("准入拒绝原因"))
                        if (opportunityFlexFieldCategory)
                        {
                            def i = 0
                            result?.decisionResult?.param?.warningInfo?.each {
                                opportunityFlexField = new com.next.OpportunityFlexField(name: it, description: "拒绝原因", dataType: "String", displayOrder: i, category: opportunityFlexFieldCategory)
                                opportunityFlexField.save(flush: true)
                                i++
                            }
                        }
                    }
                    return true
                }
                else
                {
                    println(["message": "进件请求返回失败", "status": "失败"] as grails.converters.JSON)
                    return true
                }
            }
            else
            {
                println(["message": "获取不到token", "status": "失败"] as grails.converters.JSON)
                return true
            }
        }
        else
        {
            println(["message": "获取不到订单", "status": "失败"] as grails.converters.JSON)
            return true
        }
    }

    /** @Description 中行项目对接百融接口（测度测算）
     * @Params null* @Return
     * @Author Nagelan* @DateTime 2019/01/10 0023 11:46
     */
    def educesuan = { opportunity ->
        def result
        def map
        def sentHTTPRequest = { urlString, requestData, String header ->
            try
            {
                def connection = (java.net.HttpURLConnection) urlString.openConnection()
                connection.setDoOutput(true)
                connection.setRequestMethod("POST")
                connection.setRequestProperty("Content-Type", header)
                connection.outputStream.withWriter("UTF-8") { java.io.Writer writer -> writer.write requestData }
                connection.setConnectTimeout(60000)
                result = grails.converters.JSON.parse(connection.inputStream.withReader("UTF-8") { java.io.Reader reader -> reader.text })
                return result
            }
            catch (java.lang.Exception e)
            {
                e.printStackTrace()
                println(e)
            }
        }
        //获取token请求参数
        map = "grant_type=authorization_code&client_id=test&client_secret=123456"
        result = sentHTTPRequest(new java.net.URL("http://5q6zif.natappfree.cc/oauth/token"), map, "application/x-www-form-urlencoded")
        def token = result?.token
        if (token)
        {
            def marriageStatus = opportunity?.contact?.maritalStatus
            //	已婚/未婚/离异/其他
            def age = opportunity?.contact?.age ? opportunity?.contact?.age : (new java.util.Date().format("yyyy").toInteger() - opportunity?.contact?.idNumber?.substring(6, 10)?.toInteger())
            //
            def gender = opportunity?.contact?.gender
            //	男/女
            def name = opportunity?.contact?.fullName
            def phone_no = opportunity?.contact?.cellphone
            def id_card = opportunity?.contact?.idNumber
            def loanTimeLimit = opportunity?.loanDuration
            //
            def loanAmount = opportunity?.requestedAmount
            //
            def productType = opportunity?.product?.name
            //	车位分期/家装分期
            def installmentPayment = "自主支付"
            //	商户刷卡支付/受托支付/自主支付
            def sceneCreditLimit = "200000"
            //
            def education = opportunity?.contact?.certificate?.name
            if (education in ["文盲或者半文盲", "初中", "小学", "高中", "技术学校", "中等专业学校或中等技术学校"])
            {
                education = "高中及以下"
            }
            else if (education in ["大学专科和专科学校（简称“大专”）"])
            {
                education = "大专"
            }
            else if (education in ["大学本科（简称“大学”）"])
            {
                education = "本科"
            }
            else if (education in ["研究生"])
            {
                education = "研究生及以上"
            }
            def square = ""
            def city = ""
            //房屋所在成功
            def address = ""
            if (opportunity?.houses && opportunity?.houses?.size() > 0)
            {
                opportunity?.houses?.each {
                    address += (it.address ? it.address : "") + "%"
                    square += (it.area ? it.area : "") + "%"
                    city += (it.city?.name ? it.city?.name : "") + "%"
                }
                address = address.substring(0, address.lastIndexOf("%"))
                square = square.substring(0, square.lastIndexOf("%"))
                city = city.substring(0, city.lastIndexOf("%"))
            }
            def licenseOrgan = opportunity?.contact?.authority + ""
            def channel = opportunity?.account?.level?.name + ""
            //渠道
            if (productType == "汽车分期")
            {
                sceneCreditLimit = "1000000"
            }
            else if (productType == "车位分期")
            {
                sceneCreditLimit = "300000"
            }
            else if (productType == "家装分期")
            {
                sceneCreditLimit = "300000"
            }
            else if (productType == "优客分期")
            {
                sceneCreditLimit = "200000"
            }
            def payType = ""
            //	公积金/社保
            def payRate = ""
            //	0.12/0.08
            def payAmount = ""
            //
            if (opportunity?.contact?.housingFundPersonalRatio)
            {
                payType = "公积金"
                payRate = opportunity?.contact?.housingFundPersonalRatio + ""
                payAmount = opportunity?.contact?.housingFundPersonalAmount + ""
            }
            if (opportunity?.contact?.socialInsurancePersonalRatio)
            {
                payType = "社保"
                payRate = opportunity?.contact?.socialInsurancePersonalRatio + ""
                payAmount = opportunity?.contact?.socialInsurancePersonalAmount + ""
            }
            if (opportunity?.contact?.individualIncomeTaxPersonalRatio)
            {
                payType = "个税"
                payRate = opportunity?.contact?.individualIncomeTaxPersonalRatio + ""
                payAmount = opportunity?.contact?.individualIncomeTaxPersonalAmount + ""
            }
            def industry = opportunity?.contact?.industry?.name
            //	医院/教育/金融/保险
            def monthlyIncome = opportunity?.contact?.monthlyIncome + ""
            //
            //def	whiteListMonthlyIncome = "80000"    //
            def productCode = "000020190107727696"
            map = [:]
            map.productCode = productCode
            def opportunityFlexField = com.next.OpportunityFlexField.findByNameAndCategory("百融欺诈决策结果", com.next.OpportunityFlexFieldCategory.findByOpportunityAndFlexFieldCategory(opportunity, com.next.FlexFieldCategory.findByName("百融欺诈决策结果")))
            def requestParam = [:]
            requestParam.marriageStatus = marriageStatus
            requestParam.loanTimeLimit = loanTimeLimit
            requestParam.loanAmount = loanAmount
            requestParam.productType = productType
            requestParam.installmentPayment = installmentPayment
            requestParam.payType = payType
            requestParam.payRate = payRate
            requestParam.payAmount = payAmount
            requestParam.industry = industry
            requestParam.name = name
            requestParam.id_card = id_card
            requestParam.phone_no = phone_no
            requestParam.square = square
            requestParam.city = city
            requestParam.address = address
            requestParam.licenseOrgan = licenseOrgan
            requestParam.channel = channel
            requestParam.monthlyIncome = monthlyIncome
            requestParam.sceneCreditLimit = sceneCreditLimit
            //requestParam.isWhiteListCustomer = isWhiteListCustomer
            //requestParam.whiteListMonthlyIncome = whiteListMonthlyIncome
            requestParam.age = age
            requestParam.gender = gender
            requestParam.education = education
            requestParam.repaymentAmountM6 = ""
            requestParam.unclearedMortgage = ""
            requestParam.houseAvgM6 = ""
            if (opportunityFlexField?.defaultValue)
            {
                def json = grails.converters.JSON.parse(opportunityFlexField?.defaultValue)
                requestParam.houseAvgM6 = json?.houseAvgM6 ?: ""
                requestParam.repaymentAmountM6 = json?.repaymentAmountM6 ?: ""
                requestParam.unclearedMortgage = json?.unclearedMortgage ?: ""
            }

            requestParam.poundagePayType = opportunity?.commissionPaymentMethod?.name ? opportunity?.commissionPaymentMethod?.name : "是"
            map.requestParam = requestParam
            map.token = token
            println "额度测试请求参数" + map.toString()
            result = sentHTTPRequest(new java.net.URL("http://5q6zif.natappfree.cc/decision/sync/get"), groovy.json.JsonOutput.toJson(map).toString(), "application/json")
            println "额度测试返回结果：" + result
            if (result?.stateCode == "00000")
            {
                def opportunityFlexFieldCategory
                def opportunityFlexFieldValue
                def list
                def finalRate = ""
                def score = result?.decisionResult?.score
                //存储百融授信结果
                opportunityFlexFieldCategory = com.next.OpportunityFlexFieldCategory.findByOpportunityAndFlexFieldCategory(opportunity, com.next.FlexFieldCategory.findByName("百融授信结果"))
                if (!opportunityFlexFieldCategory)
                {
                    opportunityFlexFieldCategory = new com.next.OpportunityFlexFieldCategory(opportunity: opportunity, flexFieldCategory: com.next.FlexFieldCategory.findByName("百融授信结果")).save(flush: true)
                }
                opportunityFlexField = com.next.OpportunityFlexField.findByNameAndCategory("百融授信结果", opportunityFlexFieldCategory)
                if (!opportunityFlexField)
                {
                    opportunityFlexField = new com.next.OpportunityFlexField(name: "百融授信结果", category: opportunityFlexFieldCategory, description: "百融授信结果", dataType: "String")
                }
                opportunityFlexField.value = result?.decisionResult?.result
                opportunityFlexField.save(flush: true)
                if (result?.decisionResult?.result != "拒绝" && result?.decisionResult?.param)
                {
                    opportunityFlexFieldCategory = com.next.OpportunityFlexFieldCategory.findByOpportunityAndFlexFieldCategory(opportunity, com.next.FlexFieldCategory.findByName("额度测算结果"))
                    if (opportunityFlexFieldCategory)
                    {
                        def i = 0
                        def j
                        def datas = result?.decisionResult?.param
                        if (datas)
                        {
                            finalRate = datas?.finalRate ? datas?.finalRate : 0
                            if (datas.whiteFinalCreditLine && datas.whiteBaseMaterial)
                            {
                                if (java.lang.Double.parseDouble(datas.whiteFinalCreditLine + "") > 0)
                                {
                                    opportunityFlexField = com.next.OpportunityFlexField.findByNameAndCategory(datas.whiteName, opportunityFlexFieldCategory)
                                    if (!opportunityFlexField)
                                    {
                                        opportunityFlexField = new com.next.OpportunityFlexField(name: datas.whiteName, description: datas.whiteBaseMaterial, value: datas.whiteFinalCreditLine, defaultValue: finalRate, dataType: "String", displayOrder: i, category: opportunityFlexFieldCategory)
                                        opportunityFlexField.save(flush: true)
                                        if (opportunityFlexField.description)
                                        {
                                            list = opportunityFlexField.description.split("、")
                                            j = 0
                                            list.each {
                                                opportunityFlexFieldValue = new com.next.OpportunityFlexFieldValue(field: opportunityFlexField, value: it, displayOrder: j)
                                                opportunityFlexFieldValue.save(flush: true)
                                                j += 1
                                            }
                                        }
                                        i += 1
                                    }
                                }
                            }
                            if (datas.highQualityFinalCreditLine && datas.highQualityBaseMaterial)
                            {
                                if (java.lang.Double.parseDouble(datas.highQualityFinalCreditLine + "") > 0)
                                {
                                    opportunityFlexField = com.next.OpportunityFlexField.findByNameAndCategory(datas.highQualityName, opportunityFlexFieldCategory)
                                    if (!opportunityFlexField)
                                    {
                                        opportunityFlexField = new com.next.OpportunityFlexField(name: datas.highQualityName, description: datas.highQualityBaseMaterial, value: datas.highQualityFinalCreditLine, defaultValue: finalRate, dataType: "String", displayOrder: i, category: opportunityFlexFieldCategory)
                                        opportunityFlexField.save(flush: true)
                                        if (opportunityFlexField.description)
                                        {
                                            list = opportunityFlexField.description.split("、")
                                            j = 0
                                            list.each {
                                                opportunityFlexFieldValue = new com.next.OpportunityFlexFieldValue(field: opportunityFlexField, value: it, displayOrder: j)
                                                opportunityFlexFieldValue.save(flush: true)
                                                j += 1
                                            }
                                        }
                                        i += 1
                                    }
                                }
                            }
                            if (datas.accFinalCreditLine && datas.accBaseMaterial)
                            {
                                if (java.lang.Double.parseDouble(datas.accFinalCreditLine + "") > 0)
                                {
                                    opportunityFlexField = com.next.OpportunityFlexField.findByNameAndCategory(datas.accName, opportunityFlexFieldCategory)
                                    if (!opportunityFlexField)
                                    {
                                        opportunityFlexField = new com.next.OpportunityFlexField(name: datas.accName, description: datas.accBaseMaterial, value: datas.accFinalCreditLine, defaultValue: finalRate, dataType: "String", displayOrder: i, category: opportunityFlexFieldCategory)
                                        opportunityFlexField.save(flush: true)
                                        if (opportunityFlexField.description)
                                        {
                                            list = opportunityFlexField.description.split("、")
                                            j = 0
                                            list.each {
                                                opportunityFlexFieldValue = new com.next.OpportunityFlexFieldValue(field: opportunityFlexField, value: it, displayOrder: j)
                                                opportunityFlexFieldValue.save(flush: true)
                                                j += 1
                                            }
                                        }
                                        i += 1
                                    }
                                }
                            }
                            if (datas.sSecFinalCreditLine && datas.sSecBaseMaterial)
                            {
                                if (java.lang.Double.parseDouble(datas.sSecFinalCreditLine + "") > 0)
                                {
                                    opportunityFlexField = com.next.OpportunityFlexField.findByNameAndCategory(datas.sSecName, opportunityFlexFieldCategory)
                                    if (!opportunityFlexField)
                                    {
                                        opportunityFlexField = new com.next.OpportunityFlexField(name: datas.sSecName, description: datas.sSecBaseMaterial, value: datas.sSecFinalCreditLine, defaultValue: finalRate, dataType: "String", displayOrder: i, category: opportunityFlexFieldCategory)
                                        opportunityFlexField.save(flush: true)
                                        if (opportunityFlexField.description)
                                        {
                                            list = opportunityFlexField.description.split("、")
                                            j = 0
                                            list.each {
                                                opportunityFlexFieldValue = new com.next.OpportunityFlexFieldValue(field: opportunityFlexField, value: it, displayOrder: j)
                                                opportunityFlexFieldValue.save(flush: true)
                                                j += 1
                                            }
                                        }
                                        i += 1
                                    }
                                }
                            }
                            if (datas.morFinalCreditLine && datas.morBaseMaterial)
                            {
                                if (java.lang.Double.parseDouble(datas.morFinalCreditLine + "") > 0)
                                {
                                    opportunityFlexField = com.next.OpportunityFlexField.findByNameAndCategory(datas.morName, opportunityFlexFieldCategory)
                                    if (!opportunityFlexField)
                                    {
                                        opportunityFlexField = new com.next.OpportunityFlexField(name: datas.morName, description: datas.morBaseMaterial, value: datas.morFinalCreditLine, defaultValue: finalRate, dataType: "String", displayOrder: i, category: opportunityFlexFieldCategory)
                                        opportunityFlexField.save(flush: true)
                                        if (opportunityFlexField.description)
                                        {
                                            list = opportunityFlexField.description.split("、")
                                            j = 0
                                            list.each {
                                                opportunityFlexFieldValue = new com.next.OpportunityFlexFieldValue(field: opportunityFlexField, value: it, displayOrder: j)
                                                opportunityFlexFieldValue.save(flush: true)
                                                j += 1
                                            }
                                        }
                                        i += 1
                                    }
                                }
                            }
                            if (datas.noMorFinalCreditLine && datas.noMorBaseMaterial)
                            {
                                if (java.lang.Double.parseDouble(datas.noMorFinalCreditLine + "") > 0)
                                {
                                    opportunityFlexField = com.next.OpportunityFlexField.findByNameAndCategory(datas.noMorName, opportunityFlexFieldCategory)
                                    if (!opportunityFlexField)
                                    {
                                        opportunityFlexField = new com.next.OpportunityFlexField(name: datas.noMorName, description: datas.noMorBaseMaterial, value: datas.noMorFinalCreditLine, defaultValue: finalRate, dataType: "String", displayOrder: i, category: opportunityFlexFieldCategory)
                                        opportunityFlexField.save(flush: true)
                                        if (opportunityFlexField.description)
                                        {
                                            list = opportunityFlexField.description.split("、")
                                            j = 0
                                            list.each {
                                                opportunityFlexFieldValue = new com.next.OpportunityFlexFieldValue(field: opportunityFlexField, value: it, displayOrder: j)
                                                opportunityFlexFieldValue.save(flush: true)
                                                j += 1
                                            }
                                        }
                                        i += 1
                                    }
                                }
                            }
                            if (datas.secondCardFinalCreditLine && datas.secondCardBaseMaterial)
                            {
                                if (java.lang.Double.parseDouble(datas.secondCardFinalCreditLine + "") > 0)
                                {
                                    opportunityFlexField = com.next.OpportunityFlexField.findByNameAndCategory(datas.secondCardName, opportunityFlexFieldCategory)
                                    if (!opportunityFlexField)
                                    {
                                        opportunityFlexField = new com.next.OpportunityFlexField(name: datas.secondCardName, description: datas.secondCardBaseMaterial, value: datas.secondCardFinalCreditLine, defaultValue: finalRate, dataType: "String", displayOrder: i, category: opportunityFlexFieldCategory)
                                        opportunityFlexField.save(flush: true)
                                        if (opportunityFlexField.description)
                                        {
                                            list = opportunityFlexField.description.split("、")
                                            j = 0
                                            list.each {
                                                opportunityFlexFieldValue = new com.next.OpportunityFlexFieldValue(field: opportunityFlexField, value: it, displayOrder: j)
                                                opportunityFlexFieldValue.save(flush: true)
                                                j += 1
                                            }
                                        }
                                        i += 1
                                    }
                                }
                            }
                            if (datas.generalCusFinalCreditLine && datas.generalCusBaseMaterial)
                            {
                                if (java.lang.Double.parseDouble(datas.generalCusFinalCreditLine + "") > 0)
                                {
                                    opportunityFlexField = com.next.OpportunityFlexField.findByNameAndCategory(datas.generalName, opportunityFlexFieldCategory)
                                    if (!opportunityFlexField)
                                    {
                                        opportunityFlexField = new com.next.OpportunityFlexField(name: datas.generalName, description: datas.generalCusBaseMaterial, value: datas.generalCusFinalCreditLine, defaultValue: finalRate, dataType: "String", displayOrder: i, category: opportunityFlexFieldCategory)
                                        opportunityFlexField.save(flush: true)
                                        if (opportunityFlexField.description)
                                        {
                                            list = opportunityFlexField.description.split("、")
                                            j = 0
                                            list.each {
                                                opportunityFlexFieldValue = new com.next.OpportunityFlexFieldValue(field: opportunityFlexField, value: it, displayOrder: j)
                                                opportunityFlexFieldValue.save(flush: true)
                                                j += 1
                                            }
                                        }
                                        i += 1
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    return false
                }
                return true
            }
            else
            {
                println(["message": "额度测算请求返回失败", "status": "失败"] as grails.converters.JSON)
                return true
            }
        }
        else
        {
            println(["message": "获取不到token", "status": "失败"] as grails.converters.JSON)
            return true
        }

    }

    /** @Description 合合信息身份证识别* @Params map* @Return json* @Author Nagelan* @DateTime 2018/12/27 0027 10:22
     */
    def idCard = { mapData ->
        println mapData
        def result
        def map
        def sentHTTPRequest = { urlString, file, String header ->
            try
            {
                // 设置请求头信息
                // 忽略HTTPS请求的SSL证书，必须在openConnection之前调用
                def conn = (java.net.HttpURLConnection) urlString.openConnection()
                conn.setReadTimeout(60000)
                conn.setConnectTimeout(60000)
                conn.setDoInput(true)
                conn.setDoOutput(true)
                conn.setUseCaches(false)
                conn.setRequestMethod("POST")
                conn.setRequestProperty("Charset", "utf-8")
                conn.setRequestProperty("connection", "keep-alive")
                conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)")
                conn.setRequestProperty("Content-Type", header)

                def dos = new java.io.DataOutputStream(conn.getOutputStream())

                // 文件上传
                java.io.InputStream is = file.getInputStream()
                byte[] bytes = new byte[is.available()]
                int len = 0
                while ((len = is.read(bytes)) != -1)
                {
                    dos.write(bytes, 0, len)
                }
                is.close()
                dos.flush()
                dos.close()

                // 返回值处理
                if (conn.getResponseCode() == 200)
                {
                    def response = conn.inputStream.withReader("utf-8") { java.io.Reader reader -> reader.text }
                    if (response)
                    {
                        result = grails.converters.JSON.parse(response)
                        println result
                    }
                }
                else
                {
                    println "文件上传失败，错误码：" + conn.getResponseCode()
                }
            }
            catch (Exception e)
            {
                println "File upload failure reason: "
                println e
            }
            return result
        }
        //获取token请求参数
        map = mapData.file //MultipartFile
        result = sentHTTPRequest(new java.net.URL("https://imgs-sandbox.intsig.net/icr/v3/recognize_id_card?user=guoxinda&password=7dNlwqgPPTNNPjAJ&head_portrait=0&id_number_image=0&crop_image=0"), map, "application/octet-stream")
        if (result)
        {
            println result
            return result
        }
        else
        {
            println(["message": "请求失败", "status": "失败"] as grails.converters.JSON)
            return (["message": "请求失败", "status": "失败"] as grails.converters.JSON)
        }

    }

    /** @Description 新联网核查人像比对(公安部版)
     * @Params map* @Return json* @Author Nagelan* @DateTime 2018/12/27 0027 13:42
     */
    def photo = { mapData ->
        def result
        def map
        def createSign = { String uri, parameters, String secret ->
            java.util.SortedMap parametersForSign = new java.util.TreeMap()
            parametersForSign.put("uri", uri)
            parametersForSign.putAll(parameters)
            def sb = new java.lang.StringBuilder()
            def es = parametersForSign?.entrySet()
            def it = es.iterator()
            while (it.hasNext())
            {
                Map.Entry entry = (Map.Entry) it.next()
                String k = (String) entry.getKey()
                Object v = entry.getValue()
                if (v && k != "sign" && k != "key")
                {
                    if (!it.hasNext())
                    {
                        sb.append(k).append("=").append(v)
                    }
                    else
                    {
                        sb.append(k).append("=").append(v).append("&")
                    }
                }
            }
            javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1")
            javax.crypto.spec.SecretKeySpec secretKey = new javax.crypto.spec.SecretKeySpec(secret.getBytes("UTF-8"), mac.getAlgorithm())
            mac.init(secretKey)
            byte[] hash = mac.doFinal(sb.toString().getBytes("UTF-8"))
            return new sun.misc.BASE64Encoder().encode(hash)
        }
        def sentHTTPRequest = { urlString, requestData, String header ->
            try
            {
                def connection = (java.net.HttpURLConnection) urlString.openConnection()
                connection.setDoOutput(true)
                connection.setRequestMethod("POST")
                connection.setRequestProperty("Content-Type", header)
                connection.outputStream.withWriter("UTF-8") { java.io.Writer writer -> writer.write requestData }
                connection.setConnectTimeout(10000)
                result = grails.converters.JSON.parse(connection.inputStream.withReader("UTF-8") { java.io.Reader reader -> reader.text })
                return result
            }
            catch (java.lang.Exception e)
            {
                e.printStackTrace()
                println(e)
            }
        }
        def fileToBase64 = { file ->
            java.io.InputStream is = file?.getInputStream()
            byte[] buffer = new byte[is.available()]
            is.read(buffer)
            is.close()
            def fileBase64 = new sun.misc.BASE64Encoder().encode(buffer)
            return (fileBase64)?.substring(fileBase64?.indexOf(",") + 1)
        }
        //获取token请求参数
        map = [:]
        map.appKey = "ba0319e350db4993eedcd7b2cd055264" //应用生成的 appkey
        //map.busFlowId = "" //业务流水号，业务系统唯一序列号（对账用，建议传入）
        map.nonceStr = java.util.UUID.randomUUID().toString() //随机字符串
        map.cId = mapData?.idNumber //身份证号码
        map.cName = mapData?.fullName //姓名
        map.img = fileToBase64(mapData?.file) //Base64 编码的活体抓拍的照片数据
        map.sign = createSign("/ai-cloud-cweis/netCheck/checkFaceNew", map, "f5d5e2d40217433e8f89fa11ddf2815b") //签名
        result = sentHTTPRequest(new java.net.URL("https://api-ai.cloudwalk.cn/ai-cloud-cweis/netCheck/checkFaceNew"), groovy.json.JsonOutput.toJson(map).toString(), "application/json")
        if (result)
        {
            if (result?.code == 0 || result?.code == "0")
            {
                println(["message": "请求返回成功", "status": "成功"] as grails.converters.JSON)
                return result
            }
            else
            {
                println(["message": "请求返回失败", "status": "失败"] as grails.converters.JSON)
                return result
            }
        }
        else
        {
            println(["message": "请求失败", "status": "失败"] as grails.converters.JSON)
            return (["message": "请求失败", "status": "失败"] as grails.converters.JSON)
        }

    }

    /** @Description 新人、证、公安三像比对(公安部版)
     * @Params map* @Return json* @Author Nagelan* @DateTime 2018/12/27 0027 13:42
     */
    def photo1 = { mapData ->
        def result
        def map
        def createSign = { String uri, parameters, String secret ->
            java.util.SortedMap parametersForSign = new java.util.TreeMap()
            parametersForSign.put("uri", uri)
            parametersForSign.putAll(parameters)
            def sb = new java.lang.StringBuilder()
            def es = parametersForSign?.entrySet()
            def it = es.iterator()
            while (it.hasNext())
            {
                Map.Entry entry = (Map.Entry) it.next()
                String k = (String) entry.getKey()
                Object v = entry.getValue()
                if (v && k != "sign" && k != "key")
                {
                    if (!it.hasNext())
                    {
                        sb.append(k).append("=").append(v)
                    }
                    else
                    {
                        sb.append(k).append("=").append(v).append("&")
                    }
                }
            }
            javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1")
            javax.crypto.spec.SecretKeySpec secretKey = new javax.crypto.spec.SecretKeySpec(secret.getBytes("UTF-8"), mac.getAlgorithm())
            mac.init(secretKey)
            byte[] hash = mac.doFinal(sb.toString().getBytes("UTF-8"))
            return new sun.misc.BASE64Encoder().encode(hash)
        }
        def sentHTTPRequest = { urlString, requestData, String header ->
            try
            {
                def connection = (java.net.HttpURLConnection) urlString.openConnection()
                connection.setDoOutput(true)
                connection.setRequestMethod("POST")
                connection.setRequestProperty("Content-Type", header)
                connection.outputStream.withWriter("UTF-8") { java.io.Writer writer -> writer.write requestData }
                connection.setConnectTimeout(10000)
                result = grails.converters.JSON.parse(connection.inputStream.withReader("UTF-8") { java.io.Reader reader -> reader.text })
                return result
            }
            catch (java.lang.Exception e)
            {
                e.printStackTrace()
                println(e)
            }
        }
        def fileToBase64 = { file ->
            java.io.InputStream is = file?.getInputStream()
            byte[] buffer = new byte[is.available()]
            is.read(buffer)
            is.close()
            def fileBase64 = new sun.misc.BASE64Encoder().encode(buffer)
            return (fileBase64)?.substring(fileBase64?.indexOf(",") + 1)
        }
        //获取token请求参数
        map = [:]
        map.appKey = "ba0319e350db4993eedcd7b2cd055264" //应用生成的 appkey
        //map.busFlowId = ""       //业务流水号，业务系统唯一序列号（对账用，建议传入）
        map.nonceStr = java.util.UUID.randomUUID().toString() //随机字符串
        map.cId = mapData?.idNumber //身份证号码
        map.cName = mapData?.fullName //姓名
        map.img = fileToBase64(mapData?.file) // Base64 编码的活体抓拍的照片数据
        map.idCardImg = fileToBase64(mapData?.file1) //Base64 编码的身份证人像数据
        map.sign = createSign("/ai-cloud-cweis/netCheck/checkFaceExNew", map, "f5d5e2d40217433e8f89fa11ddf2815b") //签名
        result = sentHTTPRequest(new java.net.URL("https://api-ai.cloudwalk.cn/ai-cloud-cweis/netCheck/checkFaceExNew"), groovy.json.JsonOutput.toJson(map).toString(), "application/json")
        println result
        if (result)
        {
            println result
            if (result?.code == 0 || result?.code == "0")
            {
                println(["message": "请求返回成功", "status": "成功"] as grails.converters.JSON)
                return result
            }
            else
            {
                println(["message": "请求返回失败", "status": "失败"] as grails.converters.JSON)
                return result
            }
        }
        else
        {
            println(["message": "请求失败", "status": "失败"] as grails.converters.JSON)
            return (["message": "请求失败", "status": "失败"] as grails.converters.JSON)
        }

    }
}
